import pymysql
import pandas as pd
import datetime

import pymysql.cursors

class MysqlUtils(object):
    def __init__(self):
        self.conn = pymysql.connect(
            host="localhost01",
            user="root",
            passwd="123456",
            db="tushare",
            port="3307",
            charset="utf8"
        )
        
class classIfication(object):
    def __init__(self):
        pass
    
    def get_fina_indicator(self, conn):
        cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
        
        sql = "SELECT ts_code, ann_date, eps, total_revenue_ps, undist_profit_ps, gross_margin, fcff, fcfe, tangible_asset, bps, grossprofit_margin, npta FROM financial_data WHERE ann_date >= '2023-01-01' and ann_date <= '2024-01-01'"
        
        cursor.execute(sql)
        ret = cursor.fetchall()
        
        df = pd.DataFrame(ret)
        df1 = df.dropna(subset=['eps', 'total_revenue_ps', 'undist_profit_ps', 'gross_margin', 'fcff', 'fcfe', 'tangible_asset', 'bps', 'grossprofit_margin', 'npta'])
        df1 = df1.reset_index(drop=False)
        print(df1.head)
        return df1
    
    def get_daily(self, conn, df):
        cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
        new_list = []
        
        for i in range(len(df['ts_code'])):
            ann_date = df['ann_date'][i].strftime('%Y%m%d')
            sql = "select trade_date, closes from date_1 where ts_code = \'"+ df['ts_code'][i] + "\' and trade_date > Date(\' "+ ann_date+"\')order by trade_date asc limit 20"
            # print(sql)
            cursor.execute(sql)
            ret = cursor.fetchall()
            df1 = pd.DataFrame(ret)
            print(i)
            
            try:
                if len(df) > 0:
                    max_close = df1['closes'].max()
                    min_close = df1['closes'].min()
                    the_close = df1['closes'].iloc[1]
                    
                    new_list.append({
                        'ts_code': df['ts_code'][1],
                        'ann_date': df['ann_date'][1],
                        'max_close':max_close,
                        'min_close': min_close,
                        'the_close': the_close,
                        'eps': df['eps'][1],
                        'total_revenue_ps':df['total_revenue_ps'][1],
                        'undist_profit_ps':df['undist_profit_ps'][1],
                        'fcff':df['fcff'][1],
                        'fcfe':df['fcfe'][1],
                        'tangible_asset':df['tangible_asset'][1],
                        'bps':df['bps'][1],
                        'grossprofit_margin':df['grossprofit_margin'][1],
                        'npta':df['npta'][1]
                        })
            except Exception as e:
                print(e)
                
        df2 = pd.DataFrame(new_list)
        df2.to_csv('daily.csv', index=False)

        
if __name__ == '__main__':
    mu = MysqlUtils()
    ci = classIfication()
    df = ci.get_fina_indicator(mu.conn)
    ci.get_daily(mu.conn, df)
        